package ihm.panel.admin;

import ihm.applet.KrakenApplet;
import ihm.panel.PanelInterface;
import ihm.tool.AppletConstant;
import ihm.tool.EMailVerificator;
import ihm.tool.StringUtils;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.hibernate.Session;
import org.hibernate.Transaction;

import tools.PasswordSecurity;

import bdd.standalone.bean.User;
import bdd.standalone.hibernate.HibernateUtil;

//import bdd.internal.bean.User;
//import bdd.internal.hibernate.HibernateUtil;

import enumTypes.Civility;
import enumTypes.Rank;

/**
 * Panneau permetant de créer un nouvel utilisateur.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class NewUserPanel extends JPanel implements ActionListener, PanelInterface {
	
	private static final long serialVersionUID = 1L;
	private KrakenApplet applet;
	
	private JLabel title_jl;
	
	private JLabel civ_jl, lastname_jl, name_jl, mail_jl, rank_jl;
	private JTextField lastname_jtf, name_jtf, mail_jtf;
	
	private JComboBox<Civility> civ_jcb;
	private JComboBox<Rank> rank_jcb;
	
	private JButton save_jb, reset_jb, back_jb;
	
	/**
	 * Constructeur.
	 * @param applet
	 */
	public NewUserPanel(KrakenApplet applet) {
		this.applet = applet;
		initPanel();
	}
	
	@Override
	public void initPanel() {
		this.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET);
		
		title_jl = new JLabel("<html><u>Ajout d'un nouvel utilisateur</u></html>");
		title_jl.setFont(new Font("Tahoma", Font.PLAIN, 30));
		
		civ_jl = new JLabel("Civilité");
		
		lastname_jl = new JLabel("Nom");
		
		name_jl = new JLabel("Prénom");
		
		mail_jl = new JLabel("Adresse E-mail");
		
		rank_jl = new JLabel("Rang");
		
		civ_jcb = new JComboBox<Civility>(Civility.values());
		civ_jcb.setPreferredSize(AppletConstant.FIELD_SIZE);
		
		lastname_jtf = new JTextField();
		lastname_jtf.setPreferredSize(AppletConstant.FIELD_SIZE);
		
		name_jtf = new JTextField();
		name_jtf.setPreferredSize(AppletConstant.FIELD_SIZE);
		
		mail_jtf = new JTextField();
		mail_jtf.setPreferredSize(AppletConstant.FIELD_SIZE);
		
		rank_jcb = new JComboBox<Rank>(Rank.values());
		rank_jcb.setSelectedItem(Rank.Utilisateur);
		rank_jcb.setPreferredSize(AppletConstant.FIELD_SIZE);

		save_jb = new JButton("Sauvegarder");
		save_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);
		save_jb.addActionListener(this);
		
		reset_jb = new JButton("Annuler");
		reset_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);
		reset_jb.addActionListener(this);
		
		back_jb = new JButton("Retour");
		back_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);
		back_jb.addActionListener(this);
		
		c.gridx = 0;								// position en x
		c.gridy = 0;								// position en y
		c.gridwidth = GridBagConstraints.REMAINDER;	// largeur de l'object en nombre de case, ici le reste de la ligne
		c.anchor = GridBagConstraints.WEST;			// l'ancrage de l'object
		c.fill = GridBagConstraints.NONE;			// est ce que l'object prend toute la case?
		add(title_jl, c);
		
		c.gridx = 0;
		c.gridy = 1;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(civ_jl, c);
		
		c.gridx = 1;
		c.gridy = 1;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(civ_jcb, c);
		
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(lastname_jl, c);
		
		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(lastname_jtf, c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(name_jl, c);
		
		c.gridx = 1;
		c.gridy = 3;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(name_jtf, c);
		
		c.gridx = 0;
		c.gridy = 4;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(mail_jl, c);
		
		c.gridx = 1;
		c.gridy = 4;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(mail_jtf, c);
		
		c.gridx = 0;
		c.gridy = 5;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(rank_jl, c);
		
		c.gridx = 1;
		c.gridy = 5;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(rank_jcb, c);
		
		c.gridx = 0;
		c.gridy = 6;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.WEST;
		c.fill = GridBagConstraints.NONE;
		add(save_jb, c);
		
		c.gridx = 1;
		c.gridy = 6;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.CENTER;
		c.fill = GridBagConstraints.NONE;
		add(reset_jb, c);
		
		c.gridx = 2;
		c.gridy = 6;
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.NONE;
		add(back_jb, c);
	}
	
	/**
	 * Reset les champs de saisie.
	 */
	public void resetFields() {
		this.civ_jcb.setSelectedItem(Civility.Monsieur);
		this.rank_jcb.setSelectedItem(Rank.Utilisateur);
		this.lastname_jtf.setText("");
		this.name_jtf.setText("");
		this.mail_jtf.setText("");
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Session session = applet.getSession();
		User u = (User) session.load(User.class, applet.getUser_ID());
		
		if(e.getSource().equals(save_jb)) {
			if(u.getUser_rank().equals(Rank.Administrateur)) {
				if(!lastname_jtf.getText().equalsIgnoreCase("") &&
						!name_jtf.getText().equalsIgnoreCase("") &&
						!mail_jtf.getText().equalsIgnoreCase("")) {
					if(EMailVerificator.match(mail_jtf.getText())) {
						if(!HibernateUtil.isFieldAlreadyExists(session, "bdd.internal.bean.User", "user_mail", mail_jtf.getText())) {
							Transaction tx = session.beginTransaction();
							User user = new User(lastname_jtf.getText(),name_jtf.getText(),mail_jtf.getText(),(Rank)rank_jcb.getSelectedItem(),(Civility)civ_jcb.getSelectedItem(), StringUtils.generateRandomString(12));
							session.save(user);
							user.setUser_pwd(PasswordSecurity.sha256(user.getUser_pwd_default(),user.getUser_seedPwd()));
							session.save(user);
							tx.commit();
							//Debug
							//System.out.println("User "+ user.getUser_mail() +" Added");
							resetFields();
						}
						else {
							JOptionPane.showMessageDialog(this, 
									"L'identifiant saisi pour l'adresse mail existe déjà.", 
			                        "Compte Existant", 
			                        JOptionPane.ERROR_MESSAGE );
						}
					}
					else {
						JOptionPane.showMessageDialog(this, 
								"L'adresse mail indiquée n'est pas valide."
								+ "Veuillez saisir une adresse valide.", 
		                        "Adresse mail invalide", 
		                        JOptionPane.ERROR_MESSAGE );
					}
				}
				else {
					JOptionPane.showMessageDialog(this, 
							"Veuillez remplir tous les champs afin de créer un nouvel utilisateur.",
	                        "Champs non remplis", 
	                        JOptionPane.ERROR_MESSAGE );
				}
			}
		}
		else if(e.getSource().equals(reset_jb)) {
			if(u.getUser_rank().equals(Rank.Administrateur))
				resetFields();
		}
		else if(e.getSource().equals(back_jb)) {
			if(u.getUser_rank().equals(Rank.Administrateur))
				((AdministrationPanel) getParent()).setPanel("Lister");
		}
		session.close();
	}
	
}
